<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="650px" @ok="handleSubmit"
    destroyOnClose>
    <BasicForm @register="registerForm">
      <template #fileSizeLimit="{ model, field }">
        <a-input v-model:value="model[field]" placeholder="请输入限制大小" suffix="KB" />
      </template>
    </BasicForm>

  </BasicDrawer>
</template>
<script lang="ts" setup>
import {computed, ref, unref, useAttrs} from 'vue';
import {BasicForm, useForm} from '/@/components/Form';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {formSchema} from '../fileConfig.data';
import {saveOrUpdateFileConfig} from '../fileConfig.api';
import {useMessage} from '/@/hooks/web/useMessage';

const { createMessage } = useMessage();
// 声明Emits
const emit = defineEmits(['success', 'register']);
const attrs = useAttrs()
const isUpdate = ref(true);
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  wrapperCol: {
    md: { span: 20 },
    sm: { span: 20 },
  },
  
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false
});
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  resetFields();
  isUpdate.value = !!data?.isUpdate;
  setDrawerProps({ confirmLoading: false });
  let fileTypeLimit = []
  if (data.record.fileTypeLimit) {
    fileTypeLimit = data.record.fileTypeLimit.split(',')
  }
  if (unref(isUpdate)) {
    setFieldsValue({
      ...data.record, fileTypeLimit,
    });
  }
  setProps({ disabled: !attrs.showFooter })
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增文件配置' : '编辑文件配置'));

async function handleSubmit() {
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: true });

    const form : any = {...values}
    console.log("domainTarget: ", form);

    await saveOrUpdateFileConfig(form, isUpdate.value);
    closeDrawer();
    emit('success');
    createMessage.success(`${getTitle.value}成功`)
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
